package com.campus.service.impl;

import com.campus.dao.ActivityDao;
import com.campus.dto.ActivityCreateDto;
import com.campus.dto.ActivityQueryDto;
import com.campus.model.Activity;
import com.campus.service.ActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @desc: 活动服务层实现类
 * @author: hjm
 * @date: 2024/11/12 15.41
 */
@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityDao activityDao;

    /**
     * 创建活动
     *
     * @param activityCreateDto 活动创建DTO对象
     * @return 创建的活动对象
     */
    @Override
    public Activity createActivity(ActivityCreateDto activityCreateDto) {
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityCreateDto, activity);
        activity.setCreatedTime(new Date());
        activityDao.createActivity(activity);
        return activity;
    }

    /**
     * 更新活动
     *
     * @param id 活动ID
     * @param activityCreateDto 活动创建DTO对象
     * @return 更新后的活动对象
     */
    @Override
    public Activity updateActivity(int id, ActivityCreateDto activityCreateDto) {
        Activity activity = activityDao.queryActivities(null, null, null)
                .stream()
                .filter(a -> a.getId() == id)
                .findFirst()
                .orElse(null);
        if (activity == null) {
            throw new RuntimeException("活动不存在，无法更新");
        }
        BeanUtils.copyProperties(activityCreateDto, activity);
        activity.setId((long) id);
        activityDao.updateActivity(activity);
        return activity;
    }

    /**
     * 发布活动
     *
     * @param id 活动ID
     * @return 是否发布成功
     */
    @Override
    public boolean publishActivity(int id) {
        int rowsAffected = activityDao.publishActivity(id);
        return rowsAffected > 0;
    }

    /**
     * 查询活动列表
     *
     * @param activityQueryDto 活动查询DTO对象
     * @return 活动列表
     */
    @Override
    public List<Activity> queryActivities(ActivityQueryDto activityQueryDto) {
        return activityDao.queryActivities(activityQueryDto.getStatus(), activityQueryDto.getNameKeyword(), activityQueryDto.getSortBy());
    }
}